package com.zhuoyue.system.util.xml;


import com.zhuoyue.common.exception.ServiceException;
import com.zhuoyue.system.util.api.XmlParse;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.Iterator;


/**
 * ClassName: XmlParse <br/>
 * Description: <br/>
 * date: 2019/3/12 17:31<br/>
 *
 * @author wjming<br />
 * @version 1.0
 */
public class XmlParseByTypeAndCode {
    SAXReader reader = new SAXReader();

    /**
     * xml文件读取
     *
     * @param type
     * @param code
     * @return
     * @throws ServiceException
     */
    public XmlParse getKeyAndSecret(String type, String code, String path) throws ServiceException { //如果是推送第一个参数就写jpush,如果是短信就写sms
        if (StringUtils.isEmpty(type) || StringUtils.isEmpty(code)) {
            throw new ServiceException("0001", "请确保填写信息正确");
        }
        XmlParse xmlParseObj = new XmlParse();
        try {
            Document document = reader.read("http://www.xml.zyzncloud.com/zy_smarthome_api/xml/SmartAppConfig.xml");
            Element root = document.getRootElement();//获取根元素
            Element typeObj = root.element(type);//获取根元素下面的子元素

            Iterator iterator = typeObj.elementIterator("objclass");//获取子元素下面的所有内容
            while (iterator.hasNext()) {
                Element itemEle = (Element) iterator.next();
                if (code.equals(itemEle.elementTextTrim("code"))) {// 拿到body下的子节点form下的字节点banlce的值,并且与传入的code做判断
                    xmlParseObj.setName(itemEle.elementTextTrim("name"));
                    xmlParseObj.setTitle(itemEle.elementTextTrim("title"));
                    xmlParseObj.setKey(itemEle.elementTextTrim("key"));
                    xmlParseObj.setCodeTemplateId(itemEle.elementTextTrim("CodeTemplateId"));
                    xmlParseObj.setSecret(itemEle.elementTextTrim("secret"));
                    xmlParseObj.setTime(itemEle.elementTextTrim("time"));
                    xmlParseObj.setUriActivity(itemEle.elementTextTrim("uri_activity"));
                    xmlParseObj.setUriAction(itemEle.elementTextTrim("uri_action"));
                    if (type.equals("home")) {
                        xmlParseObj.setImg(itemEle.elementTextTrim("img"));
                    }
                    System.out.println("xml解析参数" + xmlParseObj.toString());
                }
            }
        } catch (Exception e) {
        }
        return xmlParseObj;
    }
}
